package qrcodes

import (
	"context"
	"github.com/skip2/go-qrcode"
	"internal/store/redis"
	"internal/util"
	"math/rand"
	"strconv"
	"sync"
	"time"
)

const QrCodeExpirationTime time.Duration = 30 * time.Second

// SingedQrcode 签到二维码
func SingedQrcode(content string) (img []byte, err error) {
	// 生成二维码图片
	qr, err := qrcode.New(content, qrcode.Medium)
	if err != nil {
		util.LogSrv.Error("Sign in QR code creation failed,err=%v", err)
		return img, err
	}
	img, err = qr.PNG(256) // 获取image.Image对象
	if err != nil {
		util.LogSrv.Error("Failed to generate PNG format for check-in QR code,err=%v", err)
		return img, err
	}
	return img, nil
}

// GetHashKey 生成HashKey存储到redis
func GetHashKey(pSecretKey string) (HashKey string, err error) {
	var mtx sync.Mutex
	mtx.Lock()
	defer mtx.Unlock()
	ctx := context.Background()
	// 生成一个毫秒级别的时间种子
	seed := time.Now().UnixNano()
	rand.New(rand.NewSource(seed))
	HashKey = pSecretKey + strconv.FormatInt(time.Now().UnixMilli(), 10)
	//哈希key进行存储
	err = redis.GetRedisConn().Set(ctx, HashKey, true, QrCodeExpirationTime).Err()
	if err != nil {
		util.LogSrv.Info("[redis][string] HashKey set key=%s,err=%v", HashKey, err)
		return
	}
	ttl, err := redis.GetRedisConn().TTL(ctx, HashKey).Result()
	if err != nil {
		util.LogSrv.Info("[redis][string] HashKey ttl key=%s,err=%v", HashKey, err)
		return
	}
	util.LogSrv.Debug("[redis][string] HashKey set key=[%s],value=[%t],expireTime=[%v]", HashKey, true, ttl.Seconds())
	return HashKey, nil
}
